/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.nukc.sample.custom;

import com.github.nukc.sample.ResourceTable;
import com.github.nukc.sample.adapter.ToolbarAdapter;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.SlideDrawer;
import ohos.agp.components.TableLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * CustomToolbar
 *
 * @since 2021-04-26
 */
public class CustomToolbar extends DirectionalLayout implements Animator.StateChangedListener,
        Component.ClickedListener {

    private Boolean isSelOpen = true;
    private Image mMenuImage;
    private ListContainer mMenuListView;

    private PopupDialog mPopupWindow;
    private Image mDrawerImage;
    private Image mBackImage;
    private AnimatorProperty mAnimatorIcon;
    private AnimatorProperty mAnimatorLayout;
    private OnMenuItemSelectedListener mOnMenuItemSelectedListener;
    private OnAnimatorEndListener mOnAnimatorEndListener;
    private ItemOnClickInterface itemOnClickInterface;
    private PopupItemOnClickInterface popupitemOnClickInterface;
    private SlideDrawer slideDrawer;
    private boolean isViewPager2 = false;

    /**
     * 构造CustomToolbar
     *
     * @param context context
     */
    public CustomToolbar(Context context) {
        super(context);
        initView(context);
    }

    /**
     * 构造CustomToolbar
     *
     * @param context context
     * @param attrSet attrSet
     */
    public CustomToolbar(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initView(context);
    }

    /**
     * 构造CustomToolbar
     *
     * @param context context
     * @param attrSet attrSet
     * @param styleName styleName
     */
    public CustomToolbar(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initView(context);
    }

    /**
     * 初始化布局
     *
     * @param context context
     */
    private void initView(Context context) {
        mContext = context;
        Component layout = LayoutScatter.getInstance(context).parse(
                ResourceTable.Layout_ability_toolbar_main, this, true);
        initMenu(context, layout);
        initDrawer(context, layout);
        initBack(context, layout);
    }

    /**
     * 初始化自定义的menu样式
     *
     * @param context context
     * @param layout layout
     */
    private void initMenu(Context context, Component layout) {
        mMenuImage = (Image) layout.findComponentById(ResourceTable.Id_main_menu_image);
        mMenuImage.setClickedListener(this);
    }

    /**
     * setTitle设置标题
     *
     * @param title title
     */
    public void setTitle(String title) {
        Component layout = LayoutScatter.getInstance(getContext()).parse(
                ResourceTable.Layout_ability_toolbar_main, this, true);
        Text mainTitle = (Text) layout.findComponentById(ResourceTable.Id_main_title);
        mainTitle.setText(title);
    }

    public void setViewPager2(boolean viewPager2) {
        isViewPager2 = viewPager2;
    }

    /**
     * setTitleSize设置标题大小
     *
     * @param titleSize titleSize
     */
    public void setTitleSize(int titleSize) {
        Component layout = LayoutScatter.getInstance(getContext()).parse(
                ResourceTable.Layout_ability_toolbar_main, this, true);
        Text mainTitle = (Text) layout.findComponentById(ResourceTable.Id_main_title);
        mainTitle.setTextSize(titleSize);
    }

    /**
     * getTitleSize获取标题大小
     *
     * @return int 返回标题字体大小
     */
    public int getTitleSize() {
        Component layout = LayoutScatter.getInstance(getContext()).parse(
                ResourceTable.Layout_ability_toolbar_main, this, true);
        Text mainTitle = (Text) layout.findComponentById(ResourceTable.Id_main_title);
        return mainTitle.getTextSize();
    }

    /**
     * 初始化自定义的抽屉导航效果
     *
     * @param context context
     * @param layout layout
     */
    private void initDrawer(Context context, Component layout) {
        // 定义tootal左边的打开关闭抽屉效果
        mDrawerImage = (Image) layout.findComponentById(ResourceTable.Id_main_drawer);
        mDrawerImage.setClickedListener(this);
    }

    /**
     * 初始化返回
     *
     * @param context context
     * @param layout layout
     */
    private void initBack(Context context, Component layout) {
        // 定义tootal左边的打开关闭抽屉效果
        mBackImage = (Image) layout.findComponentById(ResourceTable.Id_main_back);
        mBackImage.setClickedListener(this);
    }


    /**
     * 模拟menu数据
     *
     * @return getMenuData
     */
    private List<String> getMenuData() {
        ArrayList<String> menuList = new ArrayList<>();
        menuList.add("show empty");
        menuList.add("show retry");
        menuList.add("show loading");
        menuList.add("show content");
        return menuList;
    }

    /**
     * 模拟Spinner数据
     *
     * @return getSpinnerData
     */
    private List<String> getSpinnerData() {
        ArrayList<String> menuList = new ArrayList<>();
        menuList.add("1/32");
        menuList.add("1/16");
        menuList.add("1/8");
        menuList.add("1/4");
        menuList.add("1/2");
        menuList.add("1/1");
        menuList.add("2/1");
        return menuList;
    }

    /**
     * 模拟drawer数据
     *
     * @return getDrawerData
     */
    public static List<String> getDrawerData() {
        ArrayList<String> drawerList = new ArrayList<>();
        drawerList.add("item1");
        drawerList.add("item2");
        drawerList.add("item3");
        drawerList.add("item4");
        drawerList.add("item5");
        return drawerList;
    }

    @Override
    public void onStart(Animator animator) {
    }

    @Override
    public void onStop(Animator animator) {
    }

    @Override
    public void onCancel(Animator animator) {
    }

    @Override
    public void onEnd(Animator animator) {
        if (mAnimatorIcon != null && animator == mAnimatorIcon) {
            mAnimatorIcon.reset();
            mAnimatorIcon.resume();
            mOnAnimatorEndListener.onEnd(isSelOpen, mDrawerImage);
        }
    }

    @Override
    public void onPause(Animator animator) {
    }

    @Override
    public void onResume(Animator animator) {
    }

    private void drawerAction() {
        slideDrawer = new SlideDrawer(mContext);
        ShapeElement shapeElement = new ShapeElement(getContext(), ResourceTable.Graphic_ms__drawable);
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#DCDCDC")));
        slideDrawer.setBackground(shapeElement);
        slideDrawer.setClickedListener(component -> {
        });
        itemOnClickInterface.onItemClick();
    }

    private void menuAction() {
        mMenuListView = new ListContainer(mContext);
        ShapeElement background = new ShapeElement(getContext(), ResourceTable.Graphic_ms__drawable);
        background.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#FFFAFAFA")));
        mMenuListView.setBackground(background);
        ToolbarAdapter adapter = new ToolbarAdapter(mContext, getMenuData());
        mMenuListView.setItemProvider(adapter);
        mMenuListView.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer parent, Component view, int position, long id) {
                if (mPopupWindow != null) {
                    mPopupWindow.destroy();
                    mPopupWindow = null;
                }
                mOnMenuItemSelectedListener.onMenuItemSelected(position);
            }
        });
        mPopupWindow = new PopupDialog(getContext(), mMenuImage);
        mPopupWindow.setCustomComponent(mMenuListView);
        mPopupWindow.setMode(TableLayout.Alignment.ALIGNMENT_TOP);
        final int valueOfX = DisplayManager.getInstance().getDefaultDisplay(getContext()).
                get().getRealAttributes().width;
        int valueOfY;
        final int listHeight = 40 * 3 * getMenuData().size();
        final int dividerNum = 2;
        final int toolBarHeight = 180;
        if (isViewPager2) {
            valueOfY = -(DisplayManager.getInstance().getDefaultDisplay(getContext()).
                    get().getRealAttributes().height) / dividerNum + listHeight;
        } else {
            valueOfY = -(DisplayManager.getInstance().getDefaultDisplay(getContext()).
                    get().getRealAttributes().height + toolBarHeight) / dividerNum + listHeight;
        }
        mPopupWindow.showOnCertainPosition(TableLayout.Alignment.ALIGNMENT_TOP, valueOfX, valueOfY);
        mPopupWindow.setDialogListener(() -> {
            if (mPopupWindow != null) {
                mPopupWindow.destroy();
                mPopupWindow = null;
            }
            return false;
        });
        popupitemOnClickInterface.onItemClick();
    }

    /**
     * 页面点击事件处理
     *
     * @param component component
     */
    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_main_drawer:
                drawerAction();
                break;
            case ResourceTable.Id_main_menu_image:
                menuAction();
                break;
            default:
                break;
        }
    }

    public void setSelOpen(Boolean selOpen) {
        isSelOpen = selOpen;
    }

    /**
     * 注销动画
     */
    public void resetAnimator() {
        if (mAnimatorIcon != null) {

        }
        if (mAnimatorLayout != null) {

        }
    }

    /**
     * OnSpinnerItemSelectedListener Spinner布局的某一个item被点击时的回调接口定义
     *
     * @since 2021-04-26
     */
    public interface OnSpinnerItemSelectedListener {

        /**
         * Spinner布局的某一个item被选中
         *
         * @param position item的下标
         */
        void onSpinnerItemSelected(int position);

        /**
         * Spinner布局的没有item被选中
         */
        void onSpinnerNothingSelected();
    }

    /**
     * 注册模仿Spinner布局的item监听回调
     *
     * @param listener listener
     */
    public void setSpinnerOnItemSelectedListener(OnSpinnerItemSelectedListener listener) {
    }

    /**
     * OnMenuItemSelectedListener Menu布局的某一个item被点击时的回调接口定义
     *
     * @since 2021-04-26
     */
    public interface OnMenuItemSelectedListener {
        /**
         * Menu布局的某一个item被选中
         *
         * @param position item的下标
         */
        void onMenuItemSelected(int position);

        /**
         * Menu布局的没有item被选中
         */
        void onMenuNothingSelected();
    }

    /**
     * 注册模仿Menu布局的item监听回调
     *
     * @param listener listener
     */
    public void setMenuOnItemSelectedListener(OnMenuItemSelectedListener listener) {
        mOnMenuItemSelectedListener = listener;
    }

    /**
     * 当动画结束时的回调接口定义
     *
     * @since 2021-04-26
     */
    public interface OnAnimatorEndListener {
        /**
         * 结束
         *
         * @param isSelOpen   布尔型
         * @param drawerImage image组件
         */
        void onEnd(Boolean isSelOpen, Image drawerImage);
    }

    /**
     * 注册动画结束的监听回调
     *
     * @param listener listener
     */
    public void setOnAnimatorEndListener(OnAnimatorEndListener listener) {
        mOnAnimatorEndListener = listener;
    }

    /**
     * ItemOnClickInterface回调接口
     *
     * @since 2021-04-26
     */
    public interface ItemOnClickInterface {
        /**
         * onItemClick点击事件
         */
        void onItemClick();
    }

    /**
     * popoupItemOnClickInterface回调接口
     *
     * @since 2021-04-26
     */
    public interface PopupItemOnClickInterface {
        /**
         * onItemClick点击事件
         */
        void onItemClick();
    }

    public void setItemOnClickInterface(ItemOnClickInterface thisItemOnClickInterface) {
        this.itemOnClickInterface = thisItemOnClickInterface;
    }

    public void setPopupItemOnClickInterface(PopupItemOnClickInterface thisItemOnClickInterface) {
        this.popupitemOnClickInterface = thisItemOnClickInterface;
    }
}
